
import Typer from '../libs/typer.js';
import data from './data.js';

const print = function () {
    var index = Math.floor((Math.random() * data.length));

    const typer = new Typer({
        element: document.querySelector('.main-container'),
        context: data[index],
        printDelay: () => Math.random() * 20 + 70,
        splitWith: ' '
    });

    console.log(data[index].text.replaceAll(' ', ''));

    document.querySelector('.typer-cursor').classList.remove('blink');

    typer.start(() => {
        document.querySelector('.typer-cursor').classList.add('blink');
        setTimeout(function () {
            backspace(setTimeout(print, 1000));
        }, 10000);
    });

};

const backspace = function (callback = () => {}) {
    const $outputArea = document.querySelector('.typer-output-area');
    let innerText = ($outputArea.innerText || '').trim();
    innerText = innerText.slice(0, innerText.length - 1);
    $outputArea.innerText = innerText;
    if (!innerText) {
        callback();
    } else {
        setTimeout(() => {
            backspace(callback);
        }, Math.random() * 25 + 25);
    }
};

const start = function () {
    const interval = setInterval(() => {

        const $inputArea = document.querySelector('.typer-input-area');
        const $outputArea = document.querySelector('.typer-output-area');
        const $cursor = document.querySelector('.typer-cursor');

        const text = $inputArea && $inputArea.innerText.split('') || [];

        $cursor && $cursor.classList.remove('blink');
        text.pop();
        const tempArr = [...text];
        if ($outputArea) {
            $outputArea.innerText = tempArr.join('');
        }
        if ($outputArea && $outputArea.innerText.trim() === '') {
            clearInterval(interval);
            $cursor.classList.add('blink');
            setTimeout(function () {
                print();
            }, 1000);
        }
        if (!$inputArea) {
            clearInterval(interval);
            print();
        }
    }, 100);

}

start();

const themes = [
    'default',
    'light',
    'blue1',
    'blue2',
    'light2',
    'linear1'
];

document.querySelector('#theme-btn').addEventListener('click', function () {
    const $framework = document.querySelector('.framework');
    const current = $framework.getAttribute('data-theme');
    const currentIdx = themes.indexOf(current);
    let nextIdx = currentIdx + 1;
    nextIdx = nextIdx >= themes.length ? 0 : nextIdx;
    $framework.setAttribute('data-theme', themes[nextIdx]);
});
